import {getCurrentInstance, reactive, ref, toRefs} from "vue";
import {deleteRole, getRoleById, insertRole, RoleForm, updateRole, UpdateRoleForm} from "@/api/system/role";
import {ElMessage, ElMessageBox} from "element-plus";
import useButtonDisabled from "@/hooks/useButtonDisabled/useButtonDisabled";
import {Menu} from "@/views/system/menu/hooks/useTable";
import {getMenuList} from "@/api/system/menu";
import _ from "lodash"
import useTable from "@/views/system/role/hooks/useTable";
export default function useForm() {
    const instance = getCurrentInstance()
    const { btnDisabled,clearBtnDisabled}  = useButtonDisabled()
    const { getRoleDataList } = useTable()
    const roleFormReactive = reactive<{roleForm: RoleForm}>({
        roleForm:{
            roleName:'',
            roleDesc:'',
            dataStatus:1,
            menuIds:[]
        }
    })
    const rules = reactive({
        roleName:[
            {required:true,message:'请填写角色编码',trigger:'blur'},
            {min:0,max:50,message: '角色编码不能超过50个字符',trigger: 'blur'}
        ],
        roleDesc:[
            {required:true , message:'请填写角色描述',trigger:'blur'},
            {min:0,max:50,message: '角色描述不能超过50个字符',trigger: 'blur'}
        ]
    })
    const menus = ref<Menu[]>([])
    const menuArr: Menu[] =  []
    const visible = ref(false)
    let isEdit = false
    function editRole(roleId: number) {
        getRoleById(roleId).then(res=>{
            isEdit = true
            //eslint-disable-next-line
            res.data.menuIds = buildMenuIds(_.cloneDeep(res.data.menus))
            roleFormReactive.roleForm = reactive<RoleForm>(res.data)
            visible.value =true
        })
    }
    function buildMenuIds(menus: Menu[]){
        for (let i = 0; i < menus.length; i++) {
            const m =  menus[i]
            m.children = menus.filter(mm=>{
                return m.id  === mm.parentId
            })
            const children = menuArr.filter(mr=>{
                return mr.parentId === m.id
            })
            if(m.children.length!== children.length){
                menus.splice(i,1)
                i --
            }
        }
        return menus.map(m=>m.id)
    }
    function submit(e: MouseEvent) {
        //eslint-disable-next-line
        (instance?.refs.roleFormRef as any).validate((valid: boolean)=>{
            if(!valid){
                return
            }
            btnDisabled(e);
            //eslint-disable-next-line
            const checkNodes: Menu[] = (instance?.refs.menuTreeRef as any).getCheckedNodes(false,true)
            roleFormReactive.roleForm.menuIds = checkNodes.map(m=>m.id)
            if(!isEdit){
                insertRole(roleFormReactive.roleForm).then(()=>{
                    ElMessage.success("添加角色成功")
                    visible.value = false
                    getRoleDataList()
                    clearBtnDisabled(e)
                }).catch(()=>{
                    clearBtnDisabled(e)
                })
            }else {
                updateRole((roleFormReactive.roleForm as UpdateRoleForm)).then(()=>{
                    ElMessage.success("修改角色成功")
                    visible.value = false
                    getRoleDataList()
                    clearBtnDisabled(e)
                }).catch(()=>{
                    clearBtnDisabled(e)
                })
            }
        })
    }
    function resetRoleForm() {
       roleFormReactive.roleForm ={
           roleName:'',
           roleDesc:'',
           dataStatus:1,
           menuIds:[]
       }
        isEdit = false
    }
    function flatMenuTree(menus: Menu[]) {
        menus.forEach(d=>{
            menuArr.push(d)
            if (d.children) {
                flatMenuTree(d.children)
            }
        })
    }
    function getMenu() {
        getMenuList().then(res=>{
            menus.value = res.data
            flatMenuTree(res.data)
        })
    }
    async function delRole(id: number){
        await ElMessageBox.confirm("确定要删除当前角色吗","提示",{
            type:"warning"
        })
        deleteRole(id).then(()=>{
            ElMessage.success("删除成功");
            getRoleDataList()
        })
    }
    getMenu()
    return {
        ...toRefs(roleFormReactive),
        visible,
        editRole,
        resetRoleForm,
        rules,
        submit,
        menus,
        delRole
    }
}
